package com.movitech.mobile.cz.base.common.util;

import java.math.BigDecimal;
import java.text.NumberFormat;

public class NumberUtils {

	/****
	 * 字符串转换成Double型
	 * @param str
	 * @param defaultValue
	 * @return
	 */
	public static double getStrToDouble(String str, double defaultValue) {
		try {
			return Double.parseDouble(str);
		} catch (NumberFormatException nfe) {
		}
		return defaultValue;
	}
	
	/****
	 * 字符串转换成Long型
	 * @param str
	 * @param defaultValue
	 * @return
	 */
	public static long getStrToLong(String str, long defaultValue) {
		try {
			return Long.parseLong(str);
		} catch (NumberFormatException nfe) {
		}
		return defaultValue;
	}
	
	/****
	 * 字符串转换成Long型
	 * @param str
	 * @param defaultValue
	 * @return
	 */
	public static int getStrToInteger(String str, int defaultValue) {
		try {
			return Integer.parseInt(str);
		} catch (NumberFormatException nfe) {
		}
		return defaultValue;
	}
	
	public static Double toDouble(Object obj)
	{
		Double result = 0d;
		try
		{
			if (obj != null)
				result = Double.valueOf(obj.toString());
		}
		catch (Exception e)
		{
			result=0d;
		}
		return result;
	}
	
	public static Float toFloat(Object obj)
	{
		Float result = 0f;
		try
		{
			if (obj != null)
				result = Float.valueOf(obj.toString());
		}
		catch (Exception e)
		{
			result=0f;
		}
		return result;
	}
	
	public static Long toLong(Object obj)
	{
		Long result = 0L;
		try
		{
			if (obj != null)
				result = Long.parseLong(obj.toString());
		}
		catch (Exception e)
		{
			result=0L;
		}
		return result;
	}
	
	public static Integer toInteger(Object obj)
	{
		Integer result = 0;
		try
		{
			if (obj != null)
				result = Integer.valueOf(obj.toString());
		}
		catch (Exception e)
		{
			result=0;
		}
		return result;
	}
	
	public static BigDecimal toBigDecimal(Object obj)
	{
		BigDecimal result = new BigDecimal(0);
		try
		{
			if (obj != null)
				result = BigDecimal.valueOf(toDouble(obj.toString()));
		}
		catch (Exception e)
		{
			result= new BigDecimal(0);
		}
		return result;
	}

	public static String seekercentage(Double num){
		num =new BigDecimal(num).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
		NumberFormat format = NumberFormat.getPercentInstance();
		return format.format(num);
	}

	public static Double seekercentage2Double(Double num){
		return new BigDecimal(num).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
	}
}
